package com.netty.modbus.handler;

import com.netty.modbus.dto.request.ReadBody;
import com.netty.modbus.dto.request.RequestBody;
import com.netty.modbus.dto.request.WriteBody;
import com.netty.modbus.dto.response.ResponseBody;
import com.netty.modbus.repository.DevChannelRepository;
import com.netty.modbus.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;

/**
 * description: OutHandler <br>
 * date: 2021/9/30 16:01 <br>
 * @author: lwy <br>
 * version: 1.0 <br>
 */
public class OutHandler extends ChannelOutboundHandlerAdapter {
    private DevChannelRepository devChannelRepository=DevChannelRepository.getInstance();
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof ResponseBody) {
            ResponseBody responseBody = (ResponseBody) msg;
            ByteBuf buf= responseBody.encode();
            ByteBuf buf1=responseBody.encode();
            byte[] sendData=new byte[buf1.readableBytes()];
            buf1.readBytes(sendData);
            System.out.println("向设备下发信息是"+ HexUtil.byte2HexStr(sendData));
            ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("发送成功信息给设备！");
                }
            });
        } else if(msg instanceof RequestBody){
            RequestBody requestBody=(RequestBody)msg;
            ByteBuf buf= requestBody.encode();
            ByteBuf buf1=requestBody.encode();
            byte[] sendData=new byte[buf1.readableBytes()];
            buf1.readBytes(sendData);
            System.out.println("主动向设备下发信息是"+ HexUtil.byte2HexStr(sendData));
            ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    devChannelRepository.setCommand(requestBody);
                    System.out.println("主动发送成功信息给设备！");
                }
            });
        }else {
            ctx.write(msg);
        }
    }
}
